package cn.itcast.dewu.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.itcast.dewu.dto.Result;
import cn.itcast.dewu.pojo.SeckillVoucher;
import cn.itcast.dewu.service.SeckillVoucherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.itcast.dewu.pojo.Voucher;
import cn.itcast.dewu.service.VoucherService;
import cn.itcast.dewu.mapper.VoucherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.itcast.dewu.utils.RedisConstants.*;

/**
 * @author Administrator
 * @description 针对表【tb_voucher】的数据库操作Service实现
 * @createDate 2022-04-29 14:06:30
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher>
        implements VoucherService {
    @Autowired
    private SeckillVoucherService seckillVoucherService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
     * 新增秒杀卷*/
    @Transactional
    @Override
    public void addSeckillVoucher(Voucher voucher) {
        // 保存优惠券
        save(voucher);
        // 保存秒杀信息
        SeckillVoucher seckillVoucher = new SeckillVoucher();
        seckillVoucher.setVoucherId(voucher.getId());
        seckillVoucher.setStock(voucher.getStock());
        seckillVoucher.setBeginTime(voucher.getBeginTime());
        seckillVoucher.setEndTime(voucher.getEndTime());
        seckillVoucherService.save(seckillVoucher);
        /*保存秒杀库存到redis中 键为seckill:stock: + voucher.getId()
         值为 优惠卷的库存*/
        stringRedisTemplate.opsForValue().set(SECKILL_STOCK_KEY + voucher.getId(), voucher.getStock().toString());
    }

    @Autowired
    private VoucherMapper voucherMapper;

    @Override
    public Result queryVoucherOfGoods(Long goodsId) {

        String voucherList =
                stringRedisTemplate.opsForValue().get(CACHE_VOUCHER_LIST_KEY + goodsId);
        //2.判断是否命中

        if (StrUtil.isNotEmpty(voucherList)) {
            if (voucherList.equals("1")) {
                return Result.ok();
            }
            List<Voucher> vouchers = JSONUtil.toList(voucherList, Voucher.class);
            return Result.ok(voucherList);
        }
        List<Voucher> vouchers = voucherMapper.queryVoucherOfGoods(goodsId);
        if (vouchers.isEmpty()) {
            //当数据库中没有该商品时将插入一个空值用来防止缓存穿透
            stringRedisTemplate.opsForValue().
                    set(CACHE_VOUCHER_LIST_KEY + goodsId,"1",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return Result.ok();
        }
        String voucherJosn = JSONUtil.toJsonStr(vouchers);
        stringRedisTemplate.opsForValue().set(CACHE_VOUCHER_LIST_KEY + goodsId, voucherJosn, CACHE_VOUCHER_TTL, TimeUnit.SECONDS);
        return Result.ok(vouchers);
    }
}




